Main
2021-12-18

Javascript: Country Code to Flag

Here's a fun little Javascript function:

function getflag(langcode) {
	var first = langcode.charCodeAt(0) + 127397;
	var second = langcode.charCodeAt(1) + 127397;
	var flag=`&#${first};&#${second};`;
	return flag;
}

getflag("DJ")    // πŸ‡©πŸ‡―
getflag("DE")    // πŸ‡©πŸ‡ͺ
getflag("SE")    // πŸ‡ΈπŸ‡ͺ

How does this work? Instead of adding the flags of every country to the Unicode standard, Unicode Defines 26 special characters πŸ‡¦ to πŸ‡Ώ, that can be combined according ISO 3166 to form a flag. So combining πŸ‡΅ with πŸ‡ͺ will result in the flag of Peru (PE): πŸ‡΅πŸ‡ͺ. While Unicode otherwise often uses _zero_width_joiner_ to merge characters (concatenating the five characters πŸ‘© Woman, Zero Width Joiner, πŸ‘© Woman, Zero Width Joiner and πŸ‘§ Girl results in πŸ‘©β€πŸ‘©β€πŸ‘§) in this case its even enough to write the two characters next to each. Since the 26 special characters πŸ‡¦ to πŸ‡Ώ are ordered the same way as the "normal" ASCII Letters A to Z, adding a constant offset is enough. Using above function will generate the HTML Entities for the characters. If you add those to the HTML document, you will get the countries flag.

flags js


Creative Commons License Country Code to Flag by Michael F. SchΓΆnitzer is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.